package thread.synchroCode;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Ali_1123FirstIntView {

    public static void main(String[] args) {
        AwaitSignal awaitSignal = new AwaitSignal(10);
        Condition a = awaitSignal.newCondition();
        Condition b = awaitSignal.newCondition();
        Condition c = awaitSignal.newCondition();
        new Thread(() -> {
            awaitSignal.print("C", c, a);
        }).start();
        new Thread(() -> {
            awaitSignal.print("A", a, b);
        }).start();
        new Thread(() -> {
            awaitSignal.print("B", b, c);
        }).start();

        awaitSignal.lock();
        try {
            System.out.println("开始...");
            a.signal();
        } finally {
            awaitSignal.unlock();
        }
    }
    /**
     *  问题：实现一个多线程类，并用该线程类实例化3个线程A,B,C；
     *  A线程打印字符A,B线程打印字符B，C线程打印字符C；启动这3个线程，要求启动线程的顺序为C线程->B线程->A线程，并且最后输出内容为：
     * A
     * B
     * C
     * A
     * B
     * C
     * ...（每个字母都要打印10次）
     * 不能用sleep函数，注意考虑线程安全问题。编程语言不限
     *
     */

    static class AwaitSignal extends ReentrantLock {
        private int loopNumber;

        public AwaitSignal(int loopNumber) {
            this.loopNumber = loopNumber;
        }
        //            参数1 打印内容， 参数2 进入哪一间休息室, 参数3 下一间休息室
        public void print(String str, Condition current, Condition next) {
            for (int i = 0; i < loopNumber; i++) {
                lock();
                try {
                    current.await();
                    System.out.println(str);
                    next.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    unlock();
                }
            }
        }
    }
}
